<template>
  <div class="app-container">
    <el-tabs v-model="activeName" class="floor-tabs" @tab-click="handleClick">
      <!-- 遍历floorIds数组，生成楼层选项卡 -->
      <el-tab-pane
        v-for="floorId in floorIds"
        :key="floorId"
        :label="`${floorId}楼`"
        :name="floorId.toString()">
        <div class="floor-content" v-loading="loading">
          <div
            v-if="roomData[floorId] && roomData[floorId].length > 0"
            class="rooms-container">
            <!-- 遍历房间，生成房间卡片 -->
            <div
              v-for="room in roomData[floorId]"
              :key="room.roomId"
              class="room-section">
              <!-- 房间号行，包含批量设置护理员功能 -->
              <div class="room-header">
                <span class="room-title">房间号: {{ room.roomCode }}</span>
                <el-button
                  type="primary"
                  size="small"
                  class="batch-assign-btn"
                  @click="handleBatchNurseAssign(room)">
                  批量设置护理员
                </el-button>
              </div>

              <!-- 床位网格布局，每行3个 -->
              <div class="beds-grid">
                <div
                  v-for="bed in room.bedVOList"
                  :key="bed.bedId"
                  class="bed-card"
                  :class="getBedStatusClass(bed.bedStatus)">
                  <!-- 床位号和设置护理员按钮在第一行 -->
                  <div class="bed-header">
                    <span class="bed-no">床位号: {{ bed.bedNo }}</span>
                    <el-button
                      type="text"
                      size="small"
                      class="nurse-assign-btn"
                      @click="handleNurseAssign(bed)">
                      设置护理员
                    </el-button>
                  </div>

                  <!-- 床位状态 -->
                  <div class="bed-status-row">
                    <span class="bed-status">{{
                      getBedStatusText(bed.bedStatus)
                    }}</span>
                  </div>

                  <!-- 床位详细信息 -->
                  <div class="bed-details">
                    <div class="elder-info">
                      <span class="label">老人姓名:</span>
                      <span class="value">{{ bed.elderName || "暂无" }}</span>
                    </div>

                    <div class="nurse-info">
                      <span class="label">护理员:</span>
                      <!-- 这里护理员是一个集合 需要遍历得到所有护理员 -->
                      <span class="value">
                        {{
                          bed.nurseNameList
                            ?.map((nurse) => nurse.nurseName)
                            .join(", ") || "当前床位暂无护理员"
                        }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div v-else-if="!loading" class="empty-state">
            <el-empty description="暂无房间数据"></el-empty>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 护理员设置对话框 -->
    <el-dialog
      v-model="nurseDialogVisible"
      title="设置护理员"
      width="500px"
      :before-close="handleDialogClose">
      <el-form :model="nurseForm" label-width="100px">
        <el-form-item label="护理员姓名">
          <el-select
            v-model="nurseForm.selectedNurses"
            multiple
            placeholder="请选择护理员"
            style="width: 100%"
            :multiple-limit="4">
            <el-option
              v-for="nurse in nurseList"
              :key="nurse.nurseId"
              :label="nurse.nurseName"
              :value="nurse.nurseId">
            </el-option>
          </el-select>
          <div class="nurse-limit-tip">最多可选择4个护理员</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button
            type="primary"
            @click="handleNurseSubmit"
            :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import {
  listFloorId,
  getRoomByFloorId,
  getNurseList,
  updateNurseBinding,
} from "@/api/service/manage";
import { ElMessage, ElMessageBox } from "element-plus";

const activeName = ref("");
//楼层id数组
const floorIds = ref([]);
//房间信息
const roomData = reactive({});
//该楼层没有房间 就显示这个空状态
const loading = ref(false);

// 护理员设置对话框相关数据
const nurseDialogVisible = ref(false);
const nurseList = ref([]);
const submitLoading = ref(false);
const nurseForm = reactive({
  selectedNurses: [],
  targetBedIds: [], // 目标床位ID数组
  isBatchMode: false, // 是否为批量模式
});

// 获取床位状态文本
const getBedStatusText = (status) => {
  const statusMap = {
    1: "已入住",
    2: "请假中",
  };
  return statusMap[status] || "未知";
};

// 获取床位状态样式类
const getBedStatusClass = (status) => {
  return {
    "bed-available": status === 1,
    "bed-occupied": status === 2,
  };
};

// 处理标签页切换
const handleClick = async (tab, event) => {
  try {
    // element plus 这个组件中 name属性在tab.props.name中
    const tabName = tab.props?.name || activeName.value;
    const floorId = parseInt(tabName);

    if (!roomData[floorId]) {
      await loadRoomData(floorId);
    }
  } catch (error) {
    console.error("Error in handleClick:", error);
    ElMessage.error("切换楼层时发生错误");
  }
};

// 加载房间数据
const loadRoomData = async (floorId) => {
  try {
    loading.value = true;
    const response = await getRoomByFloorId(floorId);
    if (response.code === 200) {
      roomData[floorId] = response.data;
    } else {
      ElMessage.error("获取房间数据失败");
    }
  } catch (error) {
    ElMessage.error("获取房间数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理单个护理员分配
const handleNurseAssign = async (bed) => {
  try {
    // 重置表单数据
    nurseForm.selectedNurses = [];
    nurseForm.targetBedIds = [bed.bedId];
    nurseForm.isBatchMode = false;

    // 获取护理员列表
    await loadNurseList();

    // 显示对话框
    nurseDialogVisible.value = true;
  } catch (error) {
    console.error("打开护理员设置对话框失败:", error);
    ElMessage.error("打开护理员设置对话框失败");
  }
};

// 处理批量护理员分配
const handleBatchNurseAssign = async (room) => {
  try {
    // 重置表单数据
    nurseForm.selectedNurses = [];
    nurseForm.targetBedIds = room.bedVOList.map((bed) => bed.bedId);
    nurseForm.isBatchMode = true;

    // 获取护理员列表
    await loadNurseList();

    // 显示对话框
    nurseDialogVisible.value = true;
  } catch (error) {
    console.error("打开批量护理员设置对话框失败:", error);
    ElMessage.error("打开批量护理员设置对话框失败");
  }
};

// 加载护理员列表
const loadNurseList = async () => {
  try {
    const response = await getNurseList();
    if (response.code === 200) {
      nurseList.value = response.data;
    } else {
      ElMessage.error("获取护理员列表失败");
    }
  } catch (error) {
    console.error("获取护理员列表失败:", error);
    ElMessage.error("获取护理员列表失败");
  }
};

// 处理对话框关闭
const handleDialogClose = () => {
  nurseDialogVisible.value = false;
  // 重置表单数据
  nurseForm.selectedNurses = [];
  nurseForm.targetBedIds = [];
  nurseForm.isBatchMode = false;
};

// 处理护理员提交
const handleNurseSubmit = async () => {
  if (nurseForm.selectedNurses.length === 0) {
    ElMessage.warning("请至少选择一个护理员");
    return;
  }

  try {
    submitLoading.value = true;

    //把更新的护理员id集合 和床位集合发送到后端进行更新
    const requestData = {
      bedIdList: nurseForm.targetBedIds,
      nurseIdList: nurseForm.selectedNurses,
    };

    const response = await updateNurseBinding(requestData);

    if (response.code === 200) {
      ElMessage.success("护理员设置成功");
      handleDialogClose();

      // 刷新当前楼层数据
      const currentFloorId = parseInt(activeName.value);
      if (!isNaN(currentFloorId)) {
        await loadRoomData(currentFloorId);
      }
    } else {
      ElMessage.error(response.msg || "护理员设置失败");
    }
  } catch (error) {
    console.error("护理员设置失败:", error);
    ElMessage.error("护理员设置失败");
  } finally {
    submitLoading.value = false;
  }
};

// 初始化数据 获取楼层信息
const initData = async () => {
  try {
    loading.value = true;
    const response = await listFloorId();
    if (response.code === 200 && response.data.length > 0) {
      floorIds.value = response.data;
      //默认选中第一个楼层
      activeName.value = response.data[0].toString();
      // 加载第一个楼层的数据
      await loadRoomData(response.data[0]);
    } else {
      ElMessage.warning("暂无楼层数据");
    }
  } catch (error) {
    ElMessage.error("获取楼层数据失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  initData();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.floor-tabs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.floor-tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 20px;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

.floor-tabs :deep(.el-tabs__nav-wrap) {
  padding: 10px 0;
}

.floor-tabs :deep(.el-tabs__item) {
  padding: 0 20px;
  font-size: 16px;
  font-weight: 500;
  color: #666;
}

.floor-tabs :deep(.el-tabs__item.is-active) {
  color: #1890ff;
  font-weight: 600;
}

.floor-content {
  padding: 20px;
  min-height: 400px;
}

.rooms-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.room-section {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.room-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f0f2f5;
  padding: 16px 20px;
  border-bottom: 1px solid #e8e8e8;
}

.room-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.batch-assign-btn {
  background: #1890ff;
  border-color: #1890ff;
}

.beds-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  padding: 20px;
}

.bed-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
  transition: box-shadow 0.3s ease;
}

.bed-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.bed-available {
  border-color: #52c41a;
  background: #f6ffed;
}

.bed-occupied {
  border-color: #ff7875;
  background: #fff2f0;
}

.bed-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.bed-no {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.nurse-assign-btn {
  padding: 4px 8px;
  font-size: 12px;
  color: #1890ff;
  border: 1px solid #1890ff;
  border-radius: 4px;
  background: white;
}

.nurse-assign-btn:hover {
  background: #e6f7ff;
  color: #40a9ff;
}

.bed-status-row {
  margin-bottom: 12px;
}

.bed-status {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 12px;
  background: #e6f7ff;
  color: #1890ff;
  display: inline-block;
}

.bed-available .bed-status {
  background: #f6ffed;
  color: #52c41a;
}

.bed-occupied .bed-status {
  background: #fff2f0;
  color: #ff7875;
}

.bed-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.elder-info,
.nurse-info {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.label {
  color: #666;
  margin-right: 8px;
  min-width: 70px;
  font-weight: 500;
}

.value {
  color: #303133;
  font-weight: 500;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 护理员对话框样式 */
.nurse-limit-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .beds-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .beds-grid {
    grid-template-columns: 1fr;
  }

  .room-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .bed-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .bed-details {
    gap: 6px;
  }

  .elder-info,
  .nurse-info {
    font-size: 12px;
  }

  .label {
    min-width: 60px;
  }
}
</style>
